<?php
function php2js($a=false)
{
	if (is_null($a)) return 'null';
	if ($a === false) return 'false';
	if ($a === true) return 'true';
	if (is_scalar($a)) {
		if (is_float($a)) {
			// Always use "." for floats.
			$a = str_replace(",", ".", strval($a));
		}
		// All scalars are converted to strings to avoid indeterminism.
		// PHP's "1" and 1 are equal for all PHP operators, but
		// JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
		// we should get the same result in the JS frontend (string).
		// Character replacements for JSON.
		static $jsonReplaces = array(
		array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
		array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')
		);
		return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
	}
	$isList = true;
	for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
		if (key($a) !== $i) {
			$isList = false;
			break;
		}
	}
	$result = array();
	if ($isList) {
		foreach ($a as $v) {
			$result[] = php2js($v);
		}
		return '[ ' . join(', ', $result) . ' ]';
	} else {
		foreach ($a as $k => $v) {
			$result[] = php2js($k) . ': ' .php2js($v);
		}
		return '{ ' . join(', ', $result) . ' }';
	}
}


function SetCoreProperty($property=array(),$value=array())
{
	$core =& CmsCore::Get();
	if (is_array($property))
	foreach ($property as $k=>$v)
	{
		$core->$v=$value[$k];
	}
}


function getPluginProperty($plugId,$propertyName)
{
	$table = new CARXTable('cms_plugin2page',"id=$plugId",'pluginProperties');
	$data = $table->FetchRow();
	$data = unserialize($data['pluginProperties']);
	return ($data[$propertyName]);
}

function addKov($str)
{
	return "'$str'";
}



function getComboOptions($comboTable,$comboField,$selected=false,$checkedTag)
{
	$i=0;
	//print_r($selected);
	$table = new CARXTable($comboTable,'',"$comboField,id");
	$table->Open();
	while($rec=$table->GetRow())
	{
		$data[$i]['id']=$rec['id'];
		if (is_array($selected))
		if (in_array($rec['id'],$selected))
		{
			$data[$i]['checked']=$checkedTag;
		}
		$data[$i]['value']=$rec[$comboField];
		$i++;
		$table->Next();
	}

	$table->Close();
	return $data;
}

//какая-то тупая ебень оставшаяся от Егора. Где-то юзается
function r_g($field,$num = false)
{
	return $_GET[$field];
}

function getDBEditFields($userTable,$userFields,$userValues=false,$excludeMode=false,$useFldNameKeys=false,$htmlFields=false)
{

	$table = new CARXTable('admin_fieldAlias');
	if (!$excludeMode) $table->SetFilter("tabl='$userTable' AND field IN ($userFields)");
	else
	{
		if (trim($userFields))
		$table->SetFilter("tabl='$userTable' AND field NOT IN ($userFields)");
		else $table->SetFilter("tabl='$userTable'");
	}

	$table->SetOrder('ord');
	$data = $table->FetchRows();
	

	if ($userValues)
	{
		foreach ($data as $k=>$v)
		{
			$fieldList[]=$data[$k]['field'];
		}
		//$userFieldsClean=str_replace("'",'',$userFields);
		$table = new CARXTable($userTable,"id='$userValues'",implode(',',$fieldList));
		$userData=$table->FetchRow();
	}

	foreach ($data as $k=>$v)
	{
		if ($useFldNameKeys) $i=$data[$k]['field']; else $i++;
		switch ($data[$k]['type'])
		{
			case '6':
				if ($userData[$data[$k]['field']]>0)
				{
					$table = new CARXTable($data[$k]['combo'],"id={$userData[$data[$k]['field']]}",$data[$k]['comboField']);
					$realValue = $table->FetchRow();
				}
				$profileValues[$i]['alias']=$data[$k]['alias'];
				$profileValues[$i]['fldName']=$data[$k]['field'];
				$profileValues[$i]['val'] = $realValue;
				$profileValues[$i]['type'] = 'combobox';
				$profileValues[$i]['req']=$data[$k]['required'];
				$profileValues[$i]['options']=getComboOptions($data[$k]['combo'],$data[$k]['comboField'],explode(' ',$userData[$data[$k]['field']]),'selected');

				if ($_GET['mode']=='edit')$profileValues[$i]['options']=getComboOptions($data[$k]['combo'],$data[$k]['comboField'],explode(' ',$userData[$data[$k]['field']]),'selected');
				break; //комбобокс


			case '5':
				if ($userData)
				{
				 if (trim($userData[$data[$k]['field']]))
				 {
				 	$tmpus = explode('-',$userData[$data[$k]['field']]);
				 	$profileValues[$i]['daySelected']=$tmpus[2];
				 	$profileValues[$i]['monthSelected']=$tmpus[1];
				 	$profileValues[$i]['yearSelected']=$tmpus[0];
				 	
				 }
				 
				$profileValues[$i]['val'] = changeDFFromDefault($userData[$data[$k]['field']],'d.m.Y');
				}
				$profileValues[$i]['alias']=$data[$k]['alias'];
				$profileValues[$i]['fldName']=$data[$k]['field'];
				$profileValues[$i]['type']='date';
				$profileValues[$i]['days']=range(1,31);
				$profileValues[$i]['years']=range(1900,2000);
				$profileValues[$i]['req']=$data[$k]['required'];
				break;

			case '9':
				$profileValues[$i]['alias']=$data[$k]['alias'];
				$profileValues[$i]['fldName']=$data[$k]['field'];
				$profileValues[$i]['val'] = $chkdata;
				$profileValues[$i]['isarray']=true;
				$profileValues[$i]['type']='multicheckbox';
				$profileValues[$i]['req']=$data[$k]['required'];
				$profileValues[$i]['options']=getComboOptions($data[$k]['combo'],$data[$k]['comboField'],explode(',',$selectedItems),'checked');

				break; //мультичекбокс

			case '10':
				$profileValues[$i]['alias']=$data[$k]['alias'];
				$profileValues[$i]['fldName']=$data[$k]['field'];
				$profileValues[$i]['req']=$data[$k]['required'];
				$profileValues[$i]['type']='checkbox';
				break;

			default:
				$profileValues[$i]['alias']=$data[$k]['alias'];
				$profileValues[$i]['fldName']=$data[$k]['field'];
				$profileValues[$i]['req']=$data[$k]['required'];
				$profileValues[$i]['type']='edit';
				if ($userData) $profileValues[$i]['value']=$userData[$data[$k]['field']];



		}
	}
	
	if ($htmlFields && $useFldNameKeys)
	{
		foreach ($htmlFields as $k=>$v)
		{
			$profileValues[$k]['html']=stripslashes($v);
			$valuePattern = "/value='%(.*?)%'/";
			//$valueReplace = "value='{$profileValues[$k]}'";
			$mathes = preg_match_all($valuePattern,$profileValues[$k]['html'],$mach);
			if ($mach[1])
			foreach ($mach[1] as $kk=>$vv)
			{	
			$profileValues[$k]['html']=str_replace("%$vv%",$profileValues[$mach[1][$kk]]['value'],$profileValues[$k]['html']);
			}
		}
	}
	return $profileValues;
}


function checkForms($pluginId,$fildValuez,$ajax=false,$checkCaptcha,$capchaHash)
{
	$checkCaptcha=md5(trim($checkCaptcha));
	//fldValues in format fieldName=fieldValue#@@#fieldName2=fieldValue2
	//� ������� ������ ���� �������� profileFields � profileTable
	//print_r($plugId); exit;
	$fldValuesRaw=explode(ORIGINAL_DELIMITER,substr($fildValuez,0,strlen(ORIGINAL_DELIMITER)*-1));
	$editableFields = explode(',',getPluginProperty($pluginId,'profileFields'));
	$fldTable=getPluginProperty($pluginId,'profileTable');
	//print_r($fldTable);
	foreach ($fldValuesRaw as $k=>$v)
	{

		$tmp=explode('=',$v);
		if (in_array($tmp[0],$editableFields))
		{
			$fldValues[$tmp[0]]=$tmp[1];
		}
	}
	$validationParams=getFieldServerValidators($fldTable,implode(',',array_map('addKov',$editableFields)));

	$form = new Form($validationParams,$fldValues);
	if ($form->FormValid() && $checkCaptcha==$capchaHash)
	{
		return array(1,$fldTable,$fldValues);
	}
	else
	{
		if ($checkCaptcha!=$capchaHash)
		{
			//print_r(md5(trim($checkCaptcha)));
			$currentIndex = count($form->errors);
			$form->errors[$currentIndex]['field']='captcha';
			$form->errors[$currentIndex]['erroralias']=captchaError;

		}

		if ($ajax)
		{
			if ($form->errors)
			{
				print_r(fetcharray_to_simple_json($form->errors));
			}
			else
			echo '1';
		}
		return $form->errors;
	}
}

function generateJSValidation($usedTable,$tableFldStr)
{
	/*

	<script>
	$().ready(function(){
	$("#orderForm").validate({
	rules : {
	c_name : {required : true, minlength: 2},
	c_email: {required:true,email: true},
	c_order: {required:true,minlength: 5}

	},
	messages : {
	c_name : {
	required : "������� ���� ���!",
	minlength : "�������� � ��� ���! ������� ���� �� 2 �������"
	},
	c_email : {
	required : "������� ����� ����� ����������� �����!",
	email : "E-mail ������������"
	},
	c_order : {
	required : "������� ����� ������!",
	minlength : "������� �������� ����� ������!"
	}

	}
	});
	});

	</script>
	*/

	$i=0;
	$usedTable=ARX_DB_TABLE_PREFIX.$usedTable;
	$aliasTable = ARX_DB_TABLE_PREFIX.'admin_fieldAlias';
	$validatorTable = ARX_DB_TABLE_PREFIX.'cnt_validators';
	$table = new CARXTable();
	$table->SetSQL("SELECT t1.field,t2.c_clientValidator as validator,t1.required,t1.minlength,t1.maxlength,t1.uniqueFld FROM $aliasTable t1
	LEFT JOIN $validatorTable t2 ON t1.validator=t2.id WHERE t1.tabl='$usedTable' AND t1.field IN ($tableFldStr)");
	$data = $table->FetchRows();
	$rulesBlock='rules: {';
	$msgBlock='messages : {';

	foreach ($data as $k=>$v)
	{
		if ($data[$k]['required']) {$rulePart[]='required:true'; $msgPart[]='required:"'.emptyField.'"';}
		if ($data[$k]['minlength']) {$rulePart[]="minlength:{$data[$k]['minlength']}"; $msgPart[]='minlength:"'.tooShortField.'"';}
		if ($data[$k]['maxlength']) {$rulePart[]="maxlength:{$data[$k]['maxlength']}"; $msgPart[]='maxlength:"'.overflownField.'"';}
		if ($data[$k]['validator']) {$rulePart[]="{$data[$k]['validator']}:true"; $msgPart[]=$data[$k]['validator'].':"'.nonValidField.'"';}
		if ($data[$k]['uniqueFld']) {$rulePart[]='remote:"/fieldChecker/?table='.$usedTable.'&field='.$data[$k]['field'].'"'; $msgPart[]='remote:"'.nonUniqueField.'"';}
		if (is_array($rulePart))
		$rsltFldRule[$i]=$data[$k]['field'].' : {'.implode(',',$rulePart).'}';
		if (is_array($msgPart))
		$rsltFldMsg [$i] = $data[$k]['field'].' : {'.implode(',',$msgPart).'}';
		$rulePart=array();
		$msgPart = array();
		$i++;
	}
	$rulesBlock.=implode(',',$rsltFldRule).'}';
	$msgBlock.=implode(',',$rsltFldMsg).'}';
	$result = $rulesBlock.','.$msgBlock;
	return $result;
}


function checkFldUnique($table,$field,$fieldVal,$extraFilt=false)
{
	$table = new CARXTable($table,"$field='$fieldVal' $extraFilt",$field);
	$data = $table->FetchRow();

	return trim($data[0]);
}

function getFieldServerValidators($usedTable,$tableFldStr=false)
{
	$usedTable=ARX_DB_TABLE_PREFIX.$usedTable;
	$aliasTable = ARX_DB_TABLE_PREFIX.'admin_fieldAlias';
	$validatorTable = ARX_DB_TABLE_PREFIX.'cnt_validators';
	$table = new CARXTable();
	$table->SetSQL("SELECT t1.field,t2.c_serverValidator as validator,t1.required,t1.minlength,t1.maxlength,t1.uniqueFld FROM $aliasTable t1
	LEFT JOIN $validatorTable t2 ON t1.validator=t2.id WHERE t1.tabl='$usedTable'"); //AND t1.field IN ($tableFldStr)
	$data = $table->FetchRows();
	foreach ($data as $k=>$v)
	{
		if (trim($data[$k]['validator'])) $validator=$data[$k]['validator']; else $validator='noValidation';
		$result[$data[$k]['field']]['validator']=$validator;
		$result[$data[$k]['field']]['lengthParams']=array($data[$k]['required'],$data[$k]['minlength'],$data[$k]['maxlength'],$data[$k]['uniqueFld']);
		$result[$data[$k]['field']]['fldTable'] = $usedTable;
	}
	return $result;
}

function getTableLimits($rowsperpage)
{
	$pageno = Request('p','get',true);
	if (!$pageno) $pageno = 1;
	$firstrow = ($pageno-1)*$rowsperpage;
	$rows = $rowsperpage;
	$limit = array($firstrow,$rows);
	return $limit;
}

function getTablRecNum($tableName,$filter)
{
	$table = new CARXTable($tableName,$filter,"COUNT(*) as total");
	$data = $table->FetchRow();
	return $data['total'];

}

function generatePageArray($tableName,$onPage,$curPage,$filter,$maxShowed=20,$total=false)
{

	if (!$total) $total = getTablRecNum($tableName,$filter);
	//print_R($total);
	$pageAmount = ceil($total/$onPage);
	//print_r($pageAmount);
	if ($pageAmount>$maxShowed)
	{
		$toShow=$maxShowed+$curPage-(ceil($maxShowed/2));
		if ($toShow>$pageAmount) $toShow=$pageAmount;
		if ($curPage<ceil($maxShowed/2))
		{
			$startPoint=1;
		}
		else
		{
			$startPoint=$curPage-(ceil($maxShowed/2));
		}
	}
	else
	{
		$toShow=$pageAmount;
		$startPoint=1;
	}

	//echo "$startPoint - $toShow <br>";
	for ($i=$startPoint;$i<=$toShow;$i++)
	{
		$pageArray[]=$i;
		$pajeJSON.=$i.',';
	}
	$pajeJSON='['.substr($pajeJSON,0,-1).']';
	$pageArray['json']=$pajeJSON;

	return $pageArray;
}


function CutDescription($source,$cut2Size)
{
	$source=explode(" ",$source);
	$size=count($source);
	for ($i=$cut2Size; $i<=$size; $i++)
	{
		unset ($source[$i]);
	}
	$source=implode(" ", $source);
	return $source;
}


function setPageTitle($title,$addToDefaultTitle=1)
{
	SetCoreProperty(array('mTitleTagValue','addToDefaultTitle'),array($title,$addToDefaultTitle));
}

function execPluginMethod($plugName,$plugMethod,$nosmarty=1,$params=false)
{
	if (is_numeric($plugName)) //���� �������� ID �������
	{
		$table = new CARXTable('cms_plugin2page',"id=$plugName",'plugin');
		$data = $table->FetchRow();
		$plugName=$data['plugin'];
	}
	else
	{
		if (!substr_count($plugName,"cmsplg__"))
		{
			$plugName='cmsplg__'.$plugName;
		}
	}

	require_once(CMS_PLUGIN_DIR.'/'.$plugName.'.lib.php');
	$plugObj = new $plugName;
	if ($nosmarty)
	{
		$plugObj->mReturnData=1;
	}
	if (!$params)
	{
		$result = call_user_method($plugMethod,$plugObj);
	}

	else
	{
		$result = call_user_method_array($plugMethod,$plugObj,$params);
	}

	return $result;
}

function SimpleParseSetting($valueArray,$replacerArray,$setting)
{
	foreach ($valueArray as $k=>$v)
	{
		$setting=str_replace("[%$v%]",$replacerArray[$k],$setting);
	}
	return $setting;
}

function GetSetting($setting,$setting_field='c_setting_name',$table='cnt_settings',$valueFld='c_value')
{
	$tableObj=new CARXTable($table,"$setting_field='$setting'",$valueFld);
	$tableObj->Open();
	$result=$tableObj->GetField($valueFld);
	return $result;
}

function search_highlight_words($document, $search_string, $text_size = 150, $hl_prefix = "<span style='background-color: #fbe99f;'>", $hl_suffix = "</span>")
{

	$tokens = preg_split('/\s+/', $search_string);

	$first_found_position = false;
	$text_is_cut = false;

	// ������ ����� � ������� ����� (����� ������ ���� � ���� BOOLEAN ���������)
	foreach ($tokens as $token) {

		// �������� �����
		$clean_token = str_replace(array('"', '*', '+', '>', '<', '-'), '', $token);
		if ( strlen(trim($clean_token)) == 0 ) {
			continue;
		}

		// ������� ��� � ���������: chr(1).$clean_token.chr(2)
		$new_document = preg_replace('/([\s"\'!#$%&()*+,.-\/:;<=>?@\[\]{|}])('.preg_quote($clean_token, '/').'[^"\'\s0-9!#$%&()*+,.-\/:;<=>?@\[\]{|}]*)/i', '\1'.chr(1).'\2'.chr(2), ' '.$document);

		// ���� ���-�� ���� ��������
		if ( $new_document != $document ) {

			// ������ ������ ���������...
			$first_found_position = strpos($new_document, chr(1));

			// ... � ���� �����, � ����� �� ��� �� ��������...
			if ( !$text_is_cut && $first_found_position !== false ) {
				// ...�������� ����� �������� ��������� ����� ��������������� ������...
				$begin_offset = $first_found_position - floor($text_size / 2);
				if ($begin_offset < 0) {
					$begin_offset = 0;
				}
				$text_cut_length = $text_size + strlen($clean_token) + 2;
				// ������ 2? ��� ����� �� ����������� ����. � ����. ������� ���������.
				// � ��������� �� ��������, ���� ���-�� ��������� ����� � ����� ������ 1
				// ...� ������� �����
				$document = ( $begin_offset > 0 ? '... ' : '' ) . substr($new_document, $begin_offset, $text_cut_length) . ( $begin_offset + $text_cut_length < strlen($new_document) ? ' ...' : '');
				$text_is_cut = true;
			}
			else {
				$document = $new_document;
			}
		}

	}

	// ���� �� ��� ������ � �� ��������...
	if ( !$text_is_cut ) {
		// ...�� ������� ���� �� � ������
		$document = substr($document, 0, $text_size) . ($text_size < strlen($document) ? ' ...' : '');
	}
	// �������� ��� �� ������� �������...
	$document = preg_replace('/^\.\.\. [^\s]*\s+/U', '...', $document);
	// ...� ��� ����� ���������� �������
	$document = preg_replace('/\s+[^\s]* \.\.\.$/U', '...', $document);

	// ���� ����� �� �������� ����� ����������� � ����������� ������ ���������...
	if ( strrpos($document, chr(1)) > strrpos($document, chr(2)) ) {
		// ...�� ������� ����������� ���
		$document .= chr(2);
	}

	// ������� �������� ������� ��������� ���������
	$document = str_replace(chr(1), $hl_prefix, $document);
	$document = str_replace(chr(2), $hl_suffix, $document);

	return $document;
}

function getPageTree($parent_id,$level=0)
{
	$table = new CARXTable("cms_page","parent_page_id=$parent_id","*",0,-1,"ord");
	$i++;
	$table->Open();
	while ($rec = $table->GetRow())
	{
		$rec['level']=$level;
		$_SESSION['pagetree'][]=$rec;
		$table->Next();
		$result=getPageTree($rec['page_id'],$level+1);


	}

	return $result;
}

function getSiteMap()
{

	getPageTree(0,0);
	$result=$_SESSION['pagetree'];
	unset($_SESSION['pagetree']);
	return $result;

}

function exportMyAdminTable($tabler)
{
	$i=0;
	$tabler=str_replace(ARX_DB_TABLE_PREFIX,'',$tabler);
	$fileName = str_replace('cnt_','',$tabler).'.csv';
	$nonExportable = array ('id','time','letime','c_name2,c_name3,c_name4'); //���� ������� �� ���� ��������������
	$exportFile = fopen($_SERVER['DOCUMENT_ROOT'].'/exports/'.$fileName,'w');
	$tabler = ARX_DB_TABLE_PREFIX.addslashes($tabler);
	$table = new CARXTable('admin_fieldAlias',"tabl='$tabler'",'field,alias');
	$table->Open();
	while ($rec = $table->GetRow())
	{

		$aliases[$rec['field']]=$rec['alias'];

		$table->Next();

	}
	$table->Close();
	//print_r($aliases);
	$i=0;
	$table = new CARXTable();
	$table->SetSQL("SHOW FIELDS FROM $tabler");
	$table->Open();
	while ($rec=$table->GetRow())
	{
		if (!in_array($rec['Field'],$nonExportable))
		{
			$xlsFieldHeader[$i]=$aliases[$rec['Field']];
			$i++;
		}

		$table->Next();
	}
	$table->Close();

	//print_r($xlsFieldHeader);
	foreach ($xlsFieldHeader as $k=>$v)
	{
		fputs($exportFile,$v.';');
	}
	fputs($exportFile,"\n");

	$table = new CARXTable($tabler);
	//$table->SetMode(1,1);
	$data = $table->FetchRows();

	foreach ($data as $k=>$v)
	{
		foreach ($data[$k] as $key=>$value)
		{
			if (!in_array($key,$nonExportable))
			{
				if (!trim($value)) $value='Undefined';
				fputs($exportFile,$value.';');
			}
		}
		fputs($exportFile,"\n");
	}
	fclose($exportFile);
	header('Content-type: application/csv');
	header("Content-Disposition: attachment; filename=$fileName");
	$x = fread(fopen($_SERVER['DOCUMENT_ROOT']."/exports/$fileName", "rb"), filesize($_SERVER['DOCUMENT_ROOT']."/exports/$fileName"));
	echo "$x";
	exit;
}

function changeDFFromDefault($s,$f)
{
	if (!$s) return '';
	$tmp = explode("-",$s);
	return date($f,mktime(0,0,0,$tmp[1],$tmp[2],$tmp[0]));

}

function scanDirectory($path)
{
	if ($handle = opendir($path))
	{
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != "..")
			{
				//if (!is_dir($path."/".$file))
				$result[]=$file;
			}
		}
		closedir($handle);
	}
	return $result;
}

function arrayElementToJSON($arrayData)
{
	$output="[";

	foreach ($arrayData as $k=>$v)
	{
		$lastKey=count($arrayData)-1;
		$valLength=count($v);
		$x=0;
		$useParanth=false;

		foreach ($v as $key=>$val)
		{
			if ($useParanth)
			{
				$paranth=',';
			}
			else
			{
				$paranth='';
			}

			$x++;
			if ($x==$valLength)
			{
				if ($k!=$lastKey)
				$comma=',';
				else $comma='';

				$closeSymbols="}$comma";
			}
			else
			{
				$closeSymbols='';
			}
			if ($x==1) $opener='{'; else $opener='';
			$output.=$opener.$paranth."\"$key\":\"$val\"$closeSymbols";
			$useParanth=true;
		}
	}
	$output.="]";
	return $output;
}


function fetcharray_to_simple_json($arrayData,$extraKeyValue=false)
{
	//print_r($arrayData);
	$output="{\n";
	if (is_array($extraKeyValue))
	{
		$extraLastKey=count($extraKeyValue)-1;
		foreach ($extraKeyValue as $k=>$v)
		{
			if (!is_array($extraKeyValue[$k]))
			{
				$v = str_replace("\r",'',$v);
				$v = str_replace("\n",'',$v);
				//$v=str_replace("'","&#39;",$v);
			}
			else
			{

				$v = arrayElementToJSON($v);

			}
			//$v=addslashes($v);

			$output.=$k.':'.$v.",\n";

		}
	}
	$output.="rows:\n[\n";
	if (is_array($arrayData))
	foreach ($arrayData as $k=>$v)
	{
		$lastKey=count($arrayData)-1;
		$valLength=count($v);
		$x=0;
		$useParanth=false;

		foreach ($v as $key=>$val)
		{
			if ($useParanth)
			{
				$paranth=',';
			}
			else
			{
				$paranth='';
			}

			$x++;
			if ($x==$valLength)
			{
				if ($k!=$lastKey)
				$comma=',';
				else $comma='';

				$closeSymbols="}$comma\n";
			}
			else
			{
				$closeSymbols='';
			}
			if ($x==1) $opener='{'; else $opener='';
			if (is_array($val))
			{
				//print_r($val);
				$val=arrayElementToJSON($val);

				//$val = '{"Test":"1","Test2":"0"}';
			}
			else
			{
				//$val = nl2br($val);
				$val = str_replace("\r",'',$val);
				$val = str_replace("\n",'',$val);
				$val=str_replace("'","&#39;",$val);
				$val=addslashes($val);
				$val='"'.$val.'"';
			}

			$output.=$opener.$paranth."\"$key\":$val$closeSymbols";
			$useParanth=true;
		}
	}
	$output.="]\n}";
	return $output;
}

function array_to_json_string($arraydata)
{
	$lastKey=count($arraydata)-1;
	$output = "";
	$output .= "{";
	foreach($arraydata as $key=>$val){
		if (is_array($val))
		{
			$useParanth=false;
			$output .= "\"".$key."\" : [{";
			foreach($val as $subkey=>$subval)
			{
				if ($useParanth)
				{
					$paranth=',';
				}
				else
				{
					$paranth='';
				}
				$output .=$paranth."\"".$subkey."\":\"".$subval."\"";
				$useParanth=true;
			}
			if ($key!=$lastKey)
			{
				$paranth=',';
			}
			else
			{
				$paranth='';
			}
			$output .= "}]$paranth\n";
		}
		else
		{
			$output .= "\"".$key."\" : \"".$val."\",";
		}
	}
	$output=substr($output,0,-1);
	$output .= "}";
	return $output;
}


function loadLocaleMsg()
{
	$lang_id = CMS_LANG_ID;
	$table = new CARXTable('cms__locale_settings',"lang_id=$lang_id","alias,value");
	$rec = $table->FetchRows();
	foreach ($rec as $key=>$val)
	{
		$result[$val['alias']] = $val['value'];
	}
	return $result;

}
function getDirFilders($path)
{
	$allFiles=scanDirectory($path);
	if (is_array($allFiles))
	foreach ($allFiles as $k=>$v)
	{
		if (is_dir($path."/".$v))
		{
			$result[]=$v;
		}
	}

	return $result;
}

function getDwtTemplates($path)
{
	//$dwts=implode(scanDirectory($path),"");
	//preg_match_all("/(.*?)dwt/",$dwts,$matches);
	//return $matches[0];
	$dwts=scanDirectory($path);
	foreach ($dwts as $k=>$v)
	{
		if (preg_match("/\.dwt$/i",$v) && $v!='404.dwt')
		{
			$result[]=$v;
		}
	}
	return $result;
}

function jsRedirect($path)
{
	echo "
	<script>document.location='http://'+document.domain+'$path'</script>
	";
}

    function getTemplatesSelect($sel=0, $parent_id=0, $str='')
    {
        $ret='';
        $res=mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."cms__templates WHERE parent_id=$parent_id");
        while($row=mysql_fetch_assoc($res))
        {
            $selected=($row['id']==$sel)? "selected" : '';
            $ret.="<option value='{$row['id']}' $selected>$str {$row['alias']}</option>"; //
            $ret.=getTemplatesSelect($sel, $row['id'], "{$str}&gt;");
            $templates[]=$row;
        }
        return $ret;
    }

function Request($varName, $methods='get', $bIntVal = FALSE)
{
	$value = NULL;
	if ($methods=='get')
	{
		if (isset($_GET[$varName]))
		{
			$value = $_GET[$varName];
			if ($bIntVal) $value = intval($value);
		}
	}
	if ($methods=='post')
	{
		if (isset($_POST[$varName]))
		{
			$value = $_POST[$varName];
			if ($bIntVal) $value = intval($value);
		}
	}
	return $value;
}

function showCMSPage($template, $subcontent=null)
{
	global $smarty;
	global $locale;
	$smarty->assign('locale',$locale);
	$header=$smarty->fetch("../control/_templates/cms/header.tpl");
	$footer=$smarty->fetch("../control/_templates/cms/footer.tpl");

	$res=$header.$template.$subcontent.$footer;
	echo "$res";

}


function up_image($name,$size)
{
	if (!$_FILES[$name]['tmp_name']) return '';

	$str = $_FILES[$name]['name'];
	$i = strrpos($str,".");
	if (!$i) { return ""; }
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	$str = $ext;
	$path = "/images/".$size[4]."/";
	$fname = time().rand(1000,9999).".".$str;
	$path = $_SERVER['DOCUMENT_ROOT'].$path;
	$nW = $size[0];
	$nH = $size[1];
	$nWth = $size[2];
	$nHth = $size[3];
	if (is_dir($path) || @mkdir($path))
	{
		if (move_uploaded_file($_FILES[$name]['tmp_name'],$path.$fname))
		{
			if ($nW && $nH)
			{
				ResizeImage($path.$fname, $path.$fname, $nW, $nH,1,$useLogo=false);
				chmod($path.$fname,0777);
			}
			if ($nWth && $nHth)
			{
				ResizeImage($path.$fname, $path.$size[5].$fname, $nWth, $nHth,1,$useLogo=false);
			}
			print $path.$size[5].$fname;
			chmod($path.$size[5].$fname,0777);
			return $fname;
		}
	}
}



//0 - ���������� ���� � ����� �� ����� ������� ���������������
//1 - ���� ����������� �����������
//2,3 - ����� ������ � ������
//4 - ����� �� ������ �������
//5 - ����� �� �������� �������
function ResizeImage($srcFileName, $destFileName, $newWidth, $newHeight,$cutImage=false,$useLogo=false,$makePropotional=true,$srcX=0,$srcY=0,$noByBigSize=false)
{

	$size = GetImageSize($srcFileName);
	$width = $size[0];
	$height = $size[1];

	$im = ImageCreateFromJPEG($srcFileName);


	if (!$useLogo)
	{
		if ($cutImage) //� ��������
		{
			$reqProportion=$newWidth/$newHeight; //������������������, ������� ��� �����
			$imageProporion=$width/$height; //���������� ������������������ ��������� ��������.
			if ($imageProporion>$reqProportion)
			{
				//���� �������� ����
				$cutKoef=$imageProporion/$reqProportion; //�� ������� ��� ����� ��������� ������
				$srcWidth=intval($width/$cutKoef); //����� � �������� ������ ���� ������.
				$srcHeight=$height;
				$dh=0;
				$dw=intval($width-$srcWidth)/2; //����� X

			}
			else
			{
				$cutKoef=$reqProportion/$imageProporion;
				$srcHeight=intval($height/$cutKoef);
				$srcWidth=$width;
				$dw=0;
				$dh=0;
				//�������� ��� � ��������
			}


		}
		else //���������������
		{
			$srcWidth=$width;
			$srcHeight=$height;
			if ($makePropotional)
			{
				////////////���� ����� ���� ��� ������� �� ������� �������
				if (!$noByBigSize)
				if ($height>$width)
				{
					$tmpHeight = $newHeight;

					$newHeight=$newWidth;
					$newWidth=$tmpHeight;
				}
				////////////////////
				$height1 = intval($newWidth*$height/$width);
				if ($height1 > $newHeight)
				{
					$newWidth = intval($newHeight*$width/$height);
					//������ ������� ������
				}
				else
				{
					$newHeight = $height1;
					//������ ������� ������
				}
			}

			$dw=0;
			$dh=0;
		}


		$new_im = ImageCreateTrueColor($newWidth, $newHeight);
		if ($srcX) $dw=$srcX;
		if ($srcY) $dh=$srcY;

		if (!$srcX && !$srcY)
		{
			ImageCopyResampled($new_im, $im, 0, 0, $dw, $dh,
			$newWidth, $newHeight , $srcWidth, $srcHeight);
		}
		else
		{
			imagecopy($new_im,$im,0,0,$dw,$dh,$newWidth,$newHeight);
		}

		ImageJPEG($new_im, $destFileName, 90);

	}

	if ($useLogo)
	{
		//if (!$logoResource)
		//{
		$im = ImageCreateFromJPEG($srcFileName);

		$logoResource=imagecreatefrompng(LOSTLOGO);
		$logoSize=getimagesize(LOSTLOGO);
		//}
		imagecopyresampled($im,$logoResource,15,15,0,0,$logoSize[0],$logoSize[1],$logoSize[0],$logoSize[1]);
		imagejpeg($im,$srcFileName,90);

	}
}

function getUniqueDateParams($tableName,$dateField,$param='MONTH')
{
	$curYear=date("Y");
	if ($param!='YEAR')
	{
		if (is_numeric($_GET['year']))
		{
			$filter="YEAR($dateField)={$_GET['year']}";
		}
		else $filter="YEAR($dateField)=$curYear";
	}

	$table = new CARXTable($tableName,'',"DISTINCT $param($dateField)");
	$table->SetOrder($dateField);
	$table->SetFilter($filter);
	$result=$table->FetchRows();
	return $result;
}

function convertHTML2txt($inputHTML)
{
	//$res = "\nURL: {$core->mQuery->query}\n";
	// $res .= "Title: {$core->mCMSPage->mTitle}\n";
	$res .= preg_replace
	(
	"/ +/",
	" ",
	preg_replace
	(
	"/\t+/",
	" ",
	preg_replace
	(
	"/\r+/",
	"\n",
	preg_replace
	(
	"/\n+/",
	"\n",
	strip_tags($inputHTML)
	)
	)
	)
	);
	header("Content-Type: text/plain");
}

function cutImagesFromHTML($inputHTML)
{
	$regex="/\<[^>]*?img[^>]+?src[^>]*?=[^>]*?[\'\"]?([^>\s\'\"]+)[^>]*?>/is";
	$inputHTML=preg_replace($regex,'\\1',$inputHTML);
	return $inputHTML;


}

function utf8_win2 ($s)
{
	$out="";
	$c1="";
	$byte2=false;
	for ($c=0;$c<strlen($s);$c++)
	{
		$i=ord($s[$c]);
		if ($i<=127) $out.=$s[$c];
		if ($byte2)
		{
			$new_c2=($c1&3)*64+($i&63);
			$new_c1=($c1>>2)&5;
			$new_i=$new_c1*256+$new_c2;
			if ($new_i==1025)
			{
				$out_i=168;
			}
			else
			{
				if ($new_i==1105)
				{
					$out_i=184;
				}
				else
				{
					$out_i=$new_i-848;
				}
			}
			$out.=chr($out_i);
			$byte2=false;
		}
		if (($i>>5)==6)
		{
			$c1=$i;
			$byte2=true;
		}
	}
	return $out;
}

function BuildMessageText($fieldsArray)
{
	$text.="<table>";
	foreach ($fieldsArray as $k=>$v)
	{
		if (trim($v)!="")
		{

			$text.="<tr><td><b>".str_replace(array('link','c_name','c_phone','c_email','c_prim'),array('Ссылка на вакансию','Ф�?О','Телефон','E-mail','Примечание'),$k).":</b></td><td>".htmlspecialchars($v)."</td></tr>";
		}
	}
	return $text;
}

function MailAttachment($path,$mail_to)
{

	$fp = fopen($path,"rb");
	$file = fread($fp, filesize($path));
	fclose($fp);
	$subj="New vacancy apply";
	$name = "KinUp";
	$text=BuildMessageText($_POST);

	$un        = strtoupper(uniqid(time()));
	$head      = "From: job@kinup.ru\n";
	$head     .= "Subject: $subj\n";
	$head     .= "X-Mailer: Ringo CMS Mail Tool\n";
	$head     .= "Mime-Version: 1.0\n";
	$head     .= "Content-Type:multipart/mixed;";
	$head     .= "boundary=\"----------".$un."\"\n\n";
	$zag       = "------------".$un."\nContent-Type:text/html;\n";
	$zag      .= "Content-Transfer-Encoding: 8bit\n\n$text\n\n";
	$zag      .= "------------".$un."\n";
	$zag      .= "Content-Type: application/octet-stream;";
	$zag      .= "name=\"".basename($path)."\"\n";
	$zag      .= "Content-Transfer-Encoding:base64\n";
	$zag      .= "Content-Disposition:attachment;";
	$zag      .= "filename=\"".basename($path)."\"\n\n";
	$zag      .= chunk_split(base64_encode($file))."\n";


	mail($mail_to, $subj, $zag, $head);

	//break; exit;
}

?>
